package com.primb.bench.project.setting.fragment;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.dialog.widget.NormalDialog;
import com.primb.baselibs.util.DataCleanManager;
import com.primb.baselibs.util.PreferencesUtils;
import com.primb.bench.R;
import com.primb.bench.base.BaseFragment;
import com.primb.bench.common.constant.AppConstant;
import com.primb.bench.common.module.http.service.ApiClient;
import com.primb.bench.common.module.http.service.ApiService;
import com.primb.bench.common.override.HttpSubscriber;
import com.primb.bench.project.home.entity.HttpStrEntity;
import com.primb.bench.project.init.activity.LoginActivity;
import com.primb.bench.project.init.entity.LoginEntity;
import com.primb.bench.project.setting.activity.HelpActivity;
import com.primb.netlibs.converter.RxSchedulerUtils;
import com.primb.netlibs.exception.ApiException;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by Chen on 2017/4/17.
 * 功能描述：
 */

public class SettingFragment extends BaseFragment {
    @BindView(R.id.circleImageView)
    ImageView circleImageView;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_user_part)
    TextView tvUserPart;
    @BindView(R.id.tv_user_number)
    TextView tvUserNumber;
    @BindView(R.id.tv_user_clear)
    TextView tvUserClear;
    @BindView(R.id.tv_user_config)
    TextView tvUserConfig;
    @BindView(R.id.tv_user_manger)
    TextView tvUserManger;
    @BindView(R.id.btn_no_login)
    Button btnNoLogin;
    @BindView(R.id.tv_user_clear_number)
    TextView tvUserClearNumber;
    private String savePath = Environment.getExternalStorageDirectory().getPath() + AppConstant.LOAD_CACHE;
    private CompositeSubscription subscription;

    @Override
    protected int onBaseLayoutId() {
        return R.layout.fragment_set;
    }

    @Override
    protected void onBaseBindView() {

    }

    @Override
    protected void onBaseLoadData() {
        Bundle bundle = getArguments();
        LoginEntity.DataBean info = bundle.getParcelable("info");
        tvUserName.setText(info.getUserName());
        tvUserPart.setText(info.getOrgName());
        tvUserNumber.setText(info.getUserId());
        try {
            String folderSize = DataCleanManager.getCacheSize(new File(savePath));
            tvUserClearNumber.setText(folderSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
        subscription = new CompositeSubscription();
    }

    @OnClick({R.id.circleImageView, R.id.tv_user_clear, R.id.tv_user_config, R.id.tv_user_manger, R.id.btn_no_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.circleImageView:
//                Picker.from(getActivity())
//                        .count(1)
//                        .enableCamera(true)
////                        .setEngine(new GlideEngine())
//                        .setEngine(new PicassoEngine())
////                .setEngine(new ImageLoaderEngine())
////                .setEngine(new CustomEngine())
//                        .forResult(REQUEST_CODE_CHOOSE);
                break;
            case R.id.tv_user_clear:
                NormalDialog dialogClear = showAlterDialog("清除提示", "是否清除缓存？");
                dialogClear.setOnBtnClickL(null, () -> {
                    DataCleanManager.cleanApplicationData(getContext(), savePath);
                    Toast.makeText(getActivity(), "清除完毕！", Toast.LENGTH_LONG).show();
                    dialogClear.dismiss();
                    try {
                        String folderSize = DataCleanManager.getCacheSize(new File(savePath));
                        tvUserClearNumber.setText(folderSize);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
                break;
            case R.id.tv_user_config:
                Intent intent = new Intent(getActivity(), HelpActivity.class);
                intent.putExtra("isHelp",true);
                startActivity(intent);
                break;
            case R.id.tv_user_manger:
                Intent intentManager = new Intent(getActivity(), HelpActivity.class);
                intentManager.putExtra("isHelp",false);
                startActivity(intentManager);
                break;
            case R.id.btn_no_login:
                NormalDialog dialogExit = showAlterDialog("退出提示", "是否退出登录？");
                dialogExit.setOnBtnClickL(null, () -> {
//                    try {
//                        Intent intent = new Intent(getContext(), LoginActivity.class);
//                        startActivity(intent);
//                        getActivity().finish();
//                    } catch (Exception e) {
//                    }
                    exitLogin(dialogExit);
                });
                break;
            default:
        }
    }

    private void exitLogin(NormalDialog dialogExit) {
        showLoadingDialog("退出中");
        Subscription subscribe = ApiClient.initService(ApiService.class).exitLogin()
                .compose(RxSchedulerUtils.normalSchedulersTransformer())
                .subscribe(new HttpSubscriber<HttpStrEntity>(getActivity()) {
                    @Override
                    public void onCompleted() {
                        hideLoadingDialog();
                    }

                    @Override
                    public void onNext(HttpStrEntity o) {
                        if (o.isSuccess()) {
                            try {
                                Intent intent = new Intent(getContext(), LoginActivity.class);
                                startActivity(intent);
                                getActivity().finish();
                            } catch (Exception e) {
                            }
                        }
                    }

                    @Override
                    public void onError(ApiException e) {
                        Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        hideLoadingDialog();
                        if (dialogExit != null && dialogExit.isShowing()) {
                            dialogExit.dismiss();
                        }
                    }
                });
        subscription.add(subscribe);
    }

    public NormalDialog showAlterDialog(String title, String message) {
        NormalDialog dialog = new NormalDialog(getActivity());
        dialog.widthScale(0.8f);
        dialog.style(NormalDialog.STYLE_TWO);
        dialog.titleLineColor(ContextCompat.getColor(getActivity(), R.color.app_main_gray));
        dialog.title(title);
        dialog.content(message);
        dialog.dividerColor(ContextCompat.getColor(getActivity(), R.color.app_main_gray));
        dialog.show();
        return dialog;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (subscription != null) {
            subscription.clear();
        }
    }
}
